package com.ruoyi.project.system.information.controller;

import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.ruoyi.project.system.information.mapper.CustomerInformationMapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.system.information.domain.CustomerInformation;
import com.ruoyi.project.system.information.service.ICustomerInformationService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

import javax.servlet.http.HttpServletRequest;

/**
 * 微信订单Controller
 * 
 * @author xc
 * @date 2020-02-29
 */
@Controller
@RequestMapping("/system/information")
public class CustomerInformationController extends BaseController
{
    private String prefix = "system/information";

    private String prefix1 = "userinfo";

    @Autowired
    private ICustomerInformationService customerInformationService;

    @Autowired
    private CustomerInformationMapper customerInformationMapper;

    @RequiresPermissions("system:information:view")
    @GetMapping()
    public String information()
    {
        return prefix + "/information";
    }

    /**
     * 用户信息录入界面
     */
    @GetMapping("/userinfo")
    public String userInfo()
    {
        return prefix1 + "/userinfo";
    }

    /**
     * 二维码支付界面
     */
    @GetMapping("/wxQuickMark")
    public String wxQuickMark()
    {
        return prefix1 + "/wxQuickMark";
    }

//    @Log(title = "提交用户信息", businessType = BusinessType.INSERT)
//    @PostMapping("/add")
//    @ResponseBody
//    public AjaxResult insertUserInfo(String name, String phone, String address) {
//        CustomerInformation customerInformation = new CustomerInformation();
//        customerInformation.setName(name);
//        customerInformation.setPhone(phone);
//        customerInformation.setAddress(address);
//        customerInformation.setPayStatus(1);
//        customerInformation.setShipments(1);
//        customerInformation.setDel(0);
//        customerInformationService.insertCustomerInformation(customerInformation);
//
//        return AjaxResult.success("提交成功");
//    }



    @Log(title = "提交用户信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult insertUserInfo(HttpServletRequest request) {
        CustomerInformation customerInformation = new CustomerInformation();
        String name = request.getParameter("name").trim();
        String phone = request.getParameter("phone").trim();
        String address = request.getParameter("address").trim();
        // 判空
        if (name.equals("") || name == null) {
            return AjaxResult.error("姓名为空！");
        }
        if (phone.equals("") || phone == null) {
            return AjaxResult.error("电话号码为空！");
        }
        if (address.equals("") || address == null) {
            return AjaxResult.error("地址为空！");
        }
         //电话号码校验
        String regex = "^[1][3,4,5,7,8][0-9]{9}$";
        if (!phone.matches(regex)) {
            return AjaxResult.error("电话号码格式错误！");
        }

        customerInformation.setName(name);
        customerInformation.setPhone(phone);
        customerInformation.setAddress(address);
        customerInformation.setPayStatus(1);
        customerInformation.setShipments(1);
        customerInformation.setDel(0);

        // 获取ip地址
        String ip = null;
        //X-Forwarded-For：Squid 服务代理
        String ipAddresses = request.getHeader("X-Forwarded-For");
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //Proxy-Client-IP：apache 服务代理
            ipAddresses = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //WL-Proxy-Client-IP：weblogic 服务代理
            ipAddresses = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //HTTP_CLIENT_IP：有些代理服务器
            ipAddresses = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            //X-Real-IP：nginx服务代理
            ipAddresses = request.getHeader("X-Real-IP");
        }

        //有些网络通过多层代理，那么获取到的ip就会有多个，一般都是通过逗号（,）分割开来，并且第一个ip为客户端的真实IP
        if (ipAddresses != null && ipAddresses.length() != 0) {
            ip = ipAddresses.split(",")[0];
        }

        //还是不能获取到，最后再通过request.getRemoteAddr();获取
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
            ip = request.getRemoteAddr();
        }
        if (ip.equals("0:0:0:0:0:0:0:1")) {
            ip = "127.0.0.1";
        }

        // ip地址存储到对象中
        customerInformation.setRemark(ip);

        // 根据ip地址查询改用户是否已经提交了个人信息
        CustomerInformation customerInfo = customerInformationMapper.selectCustomerInformationByIp(ip);
        if (customerInfo == null) {
            customerInformationService.insertCustomerInformation(customerInformation);
        } else {
            //判断后台支付状态，如果是已支付状态则返回提示已支付
            Integer payStatus=customerInfo.getPayStatus();
            if(payStatus==0){
                return AjaxResult.error("用户已支付，不能重复提交！");
            }
            customerInformation.setUpdateTime(new Date());
            Integer updateStatus = customerInformationMapper.updateCustomerInformationByIp(customerInformation);
            if (updateStatus > 0) {
                return AjaxResult.success("更新成功！");
            } else {
                return AjaxResult.error("更新失败！");
            }
        }

        return AjaxResult.success("提交成功！");
    }


    /**
     * 查询微信订单列表
     */
    @RequiresPermissions("system:information:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(CustomerInformation customerInformation)
    {
        startPage();
        List<CustomerInformation> list = customerInformationService.selectCustomerInformationList(customerInformation);
        return getDataTable(list);
    }

//    /**
//     * 导出微信订单列表
//     */
//    @RequiresPermissions("system:information:export")
//    @PostMapping("/export")
//    @ResponseBody
//    public AjaxResult export(CustomerInformation customerInformation)
//    {
//        List<CustomerInformation> list = customerInformationService.selectCustomerInformationList(customerInformation);
//        ExcelUtil<CustomerInformation> util = new ExcelUtil<CustomerInformation>(CustomerInformation.class);
//        return util.exportExcel(list, "information");
//    }
//
//    /**
//     * 新增微信订单
//     */
//    @GetMapping("/add")
//    public String add()
//    {
//        return prefix + "/add";
//    }

//    /**
//     * 新增保存微信订单
//     */
//    @RequiresPermissions("system:information:add")
//    @Log(title = "微信订单", businessType = BusinessType.INSERT)
//    @PostMapping("/add")
//    @ResponseBody
//    public AjaxResult addSave(CustomerInformation customerInformation)
//    {
//        return toAjax(customerInformationService.insertCustomerInformation(customerInformation));
//    }

//    /**
//     * 修改微信订单
//     */
//    @GetMapping("/edit/{id}")
//    public String edit(@PathVariable("id") Long id, ModelMap mmap)
//    {
//        CustomerInformation customerInformation = customerInformationService.selectCustomerInformationById(id);
//        mmap.put("customerInformation", customerInformation);
//        return prefix + "/edit";
//    }
//
//    /**
//     * 修改保存微信订单
//     */
//    @RequiresPermissions("system:information:edit")
//    @Log(title = "微信订单", businessType = BusinessType.UPDATE)
//    @PostMapping("/edit")
//    @ResponseBody
//    public AjaxResult editSave(CustomerInformation customerInformation)
//    {
//        return toAjax(customerInformationService.updateCustomerInformation(customerInformation));
//    }


    /**
     * 支付状态改为已支付
     */
    @RequiresPermissions("system:information:payStatusPublish")
    @Log(title = "支付状态", businessType = BusinessType.INSERT)
    @PostMapping("/payStatusPublish/{id}")
    @ResponseBody
    public AjaxResult payStatusPublish(@PathVariable("id") Integer id) {
        if (null == id || "".equals(id)) {
            return AjaxResult.error("获取的id为空");
        }
        CustomerInformation customerInformation=new CustomerInformation();
        customerInformation.setId(id);
        customerInformation.setPayStatus(0);
        customerInformationService.updateCustomerInformation(customerInformation);
        return AjaxResult.success("支付状态改为已支付完成");
    }

    /**
     * 支付状态改为未支付
     */
    @RequiresPermissions("system:information:payStatusUnpublish")
    @Log(title = "支付状态", businessType = BusinessType.INSERT)
    @PostMapping("/payStatusUnpublish/{id}")
    @ResponseBody
    public AjaxResult payStatusUnpublish(@PathVariable("id") Integer id) {
        if (null == id || "".equals(id)) {
            return AjaxResult.error("获取的id为空");
        }
        CustomerInformation customerInformation = customerInformationService.selectCustomerInformationById(id);
        Integer state = customerInformation.getShipments();
        if (state == 0) {
            return AjaxResult.error("当前订单已发货，不能更改支付状态");
        }
        CustomerInformation customer=new CustomerInformation();
        customer.setId(id);
        customer.setPayStatus(1);
        customerInformationService.updateCustomerInformation(customer);
        return AjaxResult.success("支付状态改为未支付完成");
    }

    /**
     * 发货态改为已发货
     */
    @RequiresPermissions("system:information:shipmentsPublish")
    @Log(title = "发货状态", businessType = BusinessType.INSERT)
    @PostMapping("/shipmentsPublish/{id}")
    @ResponseBody
    public AjaxResult shipmentsPublish(@PathVariable("id") Integer id) {
        if (null == id || "".equals(id)) {
            return AjaxResult.error("获取的id为空");
        }
        CustomerInformation c = customerInformationService.selectCustomerInformationById(id);
        Integer state = c.getPayStatus();
        if (state == 1) {
            return AjaxResult.error("当前订单没有支付，不能改为发货状态！");
        }
        CustomerInformation customerInformation=new CustomerInformation();
        customerInformation.setId(id);
        customerInformation.setShipments(0);
        customerInformationService.updateCustomerInformation(customerInformation);
        return AjaxResult.success("发货状态改为已发货完成");
    }

    /**
     * 发货状态改为未发货
     */
    @RequiresPermissions("system:information:shipmentsUnpublish")
    @Log(title = "发货状态", businessType = BusinessType.INSERT)
    @PostMapping("/shipmentsUnpublish/{id}")
    @ResponseBody
    public AjaxResult shipmentsUnpublish(@PathVariable("id") Integer id) {
        if (null == id || "".equals(id)) {
            return AjaxResult.error("获取的id为空");
        }
        CustomerInformation customerInformation=new CustomerInformation();
        customerInformation.setId(id);
        customerInformation.setShipments(1);
        customerInformationService.updateCustomerInformation(customerInformation);
        return AjaxResult.success("发货状态改为未发货完成");
    }


    /**
     * 删除微信订单
     */
    @RequiresPermissions("system:information:remove")
    @Log(title = "微信订单", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(customerInformationService.deleteCustomerInformationByIds(ids));
    }
}
